import React, { Component, PureComponent, useRef, useState } from 'react';
import {
  StyleSheet, Text, View, Button, DeviceEventEmitter, TouchableOpacity, SafeAreaView, Dimensions, Animated,
  ScrollView, ImageBackground, useWindowDimensions, Easing
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import styles from './styles';
import {
  titleFade,
} from '../../components/animation';
import img1 from '../../../assets/1.jpeg';
import TopTabBar from '../../components/TopTabs/topTabs';
import FoldUnfold from '../../components/foldUnfold/index';

function Mine({ navigation }) {
  const buttons = [
    { key: 'A' },
    { key: 'B' },
    { key: 'C' },
    { key: 'D' },
    { key: 'E' },
  ];

  const screenWidth = Dimensions.get('screen').width;

  const testView = () => {
    const size = 60;
    const left = useState(new Animated.Value(0))[0];
    const [ isGo, setIsGo ] = useState(true);

    const onGo = (isGo) => {
      setIsGo(prev => !prev);
      Animated.timing(
        left,
        {
          toValue: isGo? screenWidth - size : 0,
          duration: 500,
          useNativeDriver: false,
        },
      ).start();
    }

    return (
      <>
        <View style={{ flexDirection: 'row', justifyContent: 'space-around'}}>
          <TouchableOpacity style={{backgroundColor: 'yellow', padding: 10}} onPress={() => onGo(isGo)}><Text>{isGo ? 'Go' : 'Back'}</Text></TouchableOpacity>
        </View>
        <Animated.View style={[
          { height: size, width: size, borderRadius: size / 2, backgroundColor: 'red' },
          {
            // transform: [{ translateX: left }]
            marginLeft: left,
            height: left,
            minHeight: size,
            maxHeight: 3 * size,
          }
        ]}
        />
      </>
    )
  }

  const foldUnfold = () => {
    const items = [
      { key: 'Sub-Item One' },
      { key: 'Sub-Item Two' },
      { key: 'Sub-Item Three' },
      { key: 'Sub-Item Four' },
    ];
    const itemsLastIndex = items.length - 1;
    return (
      <>
        <FoldUnfold
          title='This is title'
          style={{ margin: 20, padding: 10, borderWidth: 1, borderColor: '#aaa', borderRadius: 10 }}
          items={items}
        />
        { testView() }
      </>
    );
  };

  const [shown, setShown] = useState(true);
  const [btn, setBtn] = useState(true);
  const trans = useState(new Animated.Value(1))[0];
  const animatedView = () => {
    const width = 120;

    const onPress = (isGo) => {
      // setShown(isGo);
      const target = isGo ? 0 : 1;
      // console.log(`onPress: target - ${target} trans - `, trans);
      onPress2(target);
    }

    const onPress2 = (target) => {
      // const target = isGo ? 0 : 1;
      Animated.timing(
        trans,
        {
          toValue: target,
          duration: 600,
          easing: Easing.elastic(1),
          useNativeDriver: false,
        }
      ).start(() => {
        console.log('animation done - ', trans, target);
        // setShown(!shown);
        setBtn(Boolean(target));
      });
    }

    const doAnimate = () => {
      // setBtn(false);
      const target = shown ? 0 : 1;
      // trans.setValue(shown ? 1 : 0);
      // console.log('on doAnimate: ', shown, ' => trans: ', trans, ', target: ', target);
      setShown(prev => !prev);
      Animated.timing(
        trans,
        {
          toValue: target,
          duration: 600,
          // easing: Easing.elastic(1),
          useNativeDriver: false,
        }
      ).start();
    }

    const opacity = trans.interpolate({
      inputRange: [0, 1],
      outputRange: [0, 1]
    });

    const left = trans.interpolate({
      inputRange: [0, 1],
      outputRange: [screenWidth - width, 0]
    });

    const rotate = trans.interpolate({
      inputRange: [0, 1],
      outputRange: ['180deg', '0deg']
    })

    const rotateIcon = trans.interpolate({
      inputRange: [0, 1],
      // outputRange: [!shown?'30deg':'120deg', !shown?'120deg':'30deg']
      outputRange: ['0deg', '180deg']
    })

    return (
      <>
        <View style={{ alignItems: 'center' }}><Text>Animated</Text></View>
        <View style={{ flexDirection: 'row', margin: 10 }}>
          <TouchableOpacity style={styles.button} onPress={() => { onPress(true); }}><Text style={styles.btnText}>Go Away</Text></TouchableOpacity>
          <TouchableOpacity style={styles.button} onPress={() => { onPress(false); }}><Text style={styles.btnText}>Come Back</Text></TouchableOpacity>
        </View>
        <Animated.View style={[
          { backgroundColor: 'red', padding: 20, width: width, alignItems: 'center', justifyContent: 'center' },
          { opacity },
          { left },
          { transform: [{ rotate }] }
        ]}>
          <Text style={styles.btnText}>Look Here!!</Text>
        </Animated.View>
        <View style={{ flexDirection: 'row', margin: 10 }}>
          <TouchableOpacity style={styles.button} onPress={() => { doAnimate(); }} disabled={!btn}><Text style={styles.btnText}>{shown ? 'Go Away' : 'Come Back'}</Text></TouchableOpacity>
        </View>
        <View>
          <Animated.View
            style={[
              { borderWidth: 1, width: 80, height: 80, alignItems: 'center', justifyContent: 'center' },
              { transform: [{ rotate: rotateIcon }] }
            ]}
          >
            <Ionicons name={'ios-chevron-down-circle'} size={60} color={'red'} />
          </Animated.View>
        </View>
      </>
    )
  }

  const myTabs = [
    {
      key: 'My Accounts',
      content: <View style={{ height: 400, width: screenWidth, padding: 5 }} key={'2'}>{foldUnfold()}</View>,
    },
    {
      key: 'Shared Accounts',
      content: <View style={{ height: 900, width: screenWidth, padding: 5 }} key={'1'}>{animatedView()}</View>,
    },
  ];
  const marginHorizontal = 20;
  const tabDividerSpace = 10;
  const indicatorWidth = (screenWidth - marginHorizontal * 2 - tabDividerSpace * (buttons.length - 1)) / buttons.length;
  const [indicatorLeft, setIndicatorLeft] = useState(0);
  const onButtonPress = (index) => {
    const newLeft = (indicatorWidth + tabDividerSpace) * index;
    setIndicatorLeft(newLeft);
    Animated.timing(                  // 随时间变化而执行动画
      fadeAnim,                       // 动画中的变量值
      {
        toValue: newLeft,                   // 透明度最终变为1，即完全不透明
        duration: 500,              // 让动画持续一段时间
        easing: Easing.elastic(1),
        useNativeDriver: false,
      }
    ).start();
  }
  const scrollX = useRef(new Animated.Value(0)).current;
  // const images = new Array(6).fill('https://images.unsplash.com/photo-1556740749-887f6717d7e4');
  const images = [
    'https://t7.baidu.com/it/u=2529476510,3041785782&fm=193&f=GIF',
    'https://t7.baidu.com/it/u=4162611394,4275913936&fm=193&f=GIF',
    'https://t7.baidu.com/it/u=3985596329,30052956&fm=193&f=GIF',
    'https://t7.baidu.com/it/u=727460147,2222092211&fm=193&f=GIF',
    'https://t7.baidu.com/it/u=1440354408,1578911780&fm=193&f=GIF',
    'https://t7.baidu.com/it/u=2635932700,173890368&fm=193&f=GIF',
  ]


  const { width: windowWidth } = useWindowDimensions();

  const [position, setPosition] = useState(new Animated.Value(0));
  const _translateX = () => position.interpolate({
    inputRange: [0, 1],
    outputRange: [position_0, position_1] // 两个位置下，线条距离左边框的长度
  });

  const fadeAnim = useRef(new Animated.Value(0)).current;


  return (
    <ScrollView style={styles.container}>
      <SafeAreaView>
        <Text style={styles.title}>Mine</Text>
      </SafeAreaView>

      <TopTabBar data={myTabs} style={{ marginLeft: 20, marginRight: 20 }} />
      <View style={[styles.tabContainer, { marginHorizontal }]}>
        <View style={styles.buttonsContainer}>
          {
            buttons.map((item, index) => {
              return (
                <TouchableOpacity
                  style={[styles.touchAble, { width: indicatorWidth }]}
                  onPress={() => { onButtonPress(index) }}
                  key={item.key}
                >
                  <Text>{item.key}</Text>
                </TouchableOpacity>
              )
            })
          }
        </View>
        <View style={{ width: '100%', marginVertical: 5 }}>
          <Animated.View style={[
            styles.indicator,
            { width: indicatorWidth, },
            { left: fadeAnim, }
          ]} />
        </View>
      </View>
      <View>
        <SafeAreaView style={styles.container}>
          <View style={styles.scrollContainer}>
            <ScrollView
              horizontal={true}
              style={{ width: 100 }}
              pagingEnabled
              showsHorizontalScrollIndicator={false}
              onScroll={Animated.event([
                {
                  nativeEvent: {
                    contentOffset: {
                      x: scrollX
                    }
                  }
                }
              ], {
                useNativeDriver: false,
              })}
              scrollEventThrottle={1}
            >
              {images.map((image, imageIndex) => {
                // console.log('img: ',typeof image, image);
                return (
                  <View
                    style={{ width: 100, height: 250 }}
                    key={imageIndex}
                  >
                    <ImageBackground source={{ uri: image }} style={styles.card}>
                    </ImageBackground>
                  </View>
                );
              })}
            </ScrollView>
            <View style={styles.indicatorContainer}>
              {images.map((image, imageIndex) => {
                const width = scrollX.interpolate({
                  inputRange: [
                    windowWidth * (imageIndex - 1),
                    windowWidth * imageIndex,
                    windowWidth * (imageIndex + 1)
                  ],
                  outputRange: [8, 16, 8],
                  extrapolate: "clamp"
                });
                return (
                  <Animated.View
                    key={imageIndex}
                    style={[styles.normalDot, { width }]}
                  />
                );
              })}
            </View>
          </View>
        </SafeAreaView>
      </View>
    </ScrollView>
  )
}

export default Mine;
